package xyz.labmem.main.application.controller.api.file;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xyz.labmem.main.annotation.RoleValid;
import xyz.labmem.main.application.entity.sys.File;
import xyz.labmem.main.application.service.sys.impl.FileServiceImpl;
import xyz.labmem.main.error.FuncException;
import xyz.labmem.main.result.ResultUtil;
import xyz.labmem.main.result.ResultVo;
import xyz.labmem.main.sys.StaticVariable;

import javax.servlet.http.HttpServletResponse;

/**
 * @author ：刘天予
 * @date ：Created in 2020/6/16 13:37
 * @description：
 * @modified By：
 * @version: $
 */
@RestController
@Api(tags = "公用文件API")
@RequestMapping("/file")
public class PublicFileApi extends StaticVariable {

    private final FileServiceImpl fileService;

    public PublicFileApi(FileServiceImpl fileService) {
        this.fileService = fileService;
    }

    @ApiOperation("文件下载")
    @GetMapping("/download/{fileKey}")
    @RoleValid
    public void download(@PathVariable(value = "fileKey") String fileKey, HttpServletResponse response) {
        try {
            File file = new File().selectOne(new LambdaQueryWrapper<File>().eq(File::getFileKey, fileKey));
            fileService.fileDownloadByKey(response, fileKey, file.getOriginalName());
        } catch (Exception e) {
            new FuncException("文件下載失敗", e);
        }
    }

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    @RoleValid
    public ResultVo upload(@RequestParam("file") MultipartFile multipartFile, @RequestParam(value = "path", required = false) String path) {
        try {
            return ResultUtil.success("上传成功", fileService.uploadFile(multipartFile, path));
        } catch (Exception e) {
            new FuncException("文件上传失敗", e);
            return ResultUtil.failed("上传失败");
        }
    }

    @ApiOperation("删除文件")
    @PostMapping("/del")
    @RoleValid
    public ResultVo upload(@RequestBody File file) {
        try {
            return fileService.deleteFileByKey(file.getFileKey()) ? ResultUtil.success("删除成功") : ResultUtil.failed("删除失败");
        } catch (Exception e) {
            new FuncException("删除失敗", e);
            return ResultUtil.failed("删除失败");
        }
    }

}
